// Package service provides the security bulletin service
package service

import (
	"fmt"

	"github.com/sirupsen/logrus"

	"cvevulner/cve-ddd/domain"
	"cvevulner/cve-ddd/domain/obs"
	"cvevulner/cve-ddd/domain/updateinfo"
)

const (
	updateInfoFileName = "updateinfo.xml"
)

// SyncUpdateInfoToEarlyDir 将正式目录的updateinfo文件同步到early目录，这样每次提前生成的文件都是以正式目录为基准的
func SyncUpdateInfoToEarlyDir(obs obs.OBS, log *logrus.Entry, branches []string, officialDir, earlyDir string) {
	for _, b := range branches {
		officialPath := fmt.Sprintf("%s/%s/%s", officialDir, b, updateInfoFileName)
		downloadBys, err := obs.Download(officialPath)
		if err != nil {
			log.Errorf("sync download %s failed: %s", officialPath, err.Error())
			continue
		}

		earlyPath := fmt.Sprintf("%s/%s/%s", earlyDir, b, updateInfoFileName)
		if err = obs.Upload(earlyPath, downloadBys); err != nil {
			log.Errorf("sync upload %s failed: %s", earlyPath, err.Error())
		}
	}
}

// UploadUpdateInfoFile 用以以前生成updateinfo文件，以便测试验证文件正确性
func UploadUpdateInfoFile(obs obs.OBS, updateinfo updateinfo.UpdateInfo,
	log *logrus.Entry, bulletin *domain.SecurityBulletin, date, earlyDir string,
) {
	for _, branch := range bulletin.AffectedVersion {
		filePath := fmt.Sprintf("%s/%s/%s", earlyDir, branch, updateInfoFileName)
		downloadBys, err := obs.Download(filePath)
		if err != nil {
			log.Errorf("download %s failed: %s", filePath, err.Error())
			continue
		}

		data, err := updateinfo.UploadUpdateInfoXml(domain.UpdateParam{
			Sb:          bulletin,
			Date:        date,
			Branch:      branch,
			DownloadBys: downloadBys,
		})

		if err != nil {
			log.Errorf("update updateinfo of %s failed: %s", bulletin.Identification, err.Error())
			continue
		}

		if err = obs.Upload(filePath, data); err != nil {
			log.Errorf("upload %s failed: %s", filePath, err.Error())
			continue
		}
	}
}
